package com.itheima.controller;

import com.aliyuncs.exceptions.ClientException;
import com.itheima.entity.Result;
import com.itheima.resource.MessageConstant;
import com.itheima.resource.RedisConstant;
import com.itheima.resource.RedisMessageConstant;
import com.itheima.utils.SMSUtils;
import com.itheima.utils.ValidateCodeUtils;
import io.netty.handler.codec.redis.RedisMessage;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import redis.clients.jedis.JedisPool;

/**
 * 给手机发送短信
 */
@RestController
@RequestMapping("/validateCode")
public class ValidateCodeController {
    @Autowired
    private JedisPool jedisPool;

    @RequestMapping("/send2telephone.do")
    public Result validateCode(@RequestParam("telephone") String telephone){
        try {
            //使用工具类随机生成一个验证码
            Integer code = ValidateCodeUtils.generateValidateCode(4);
            //使用工具类发送短信
            //SMSUtils.sendShortMessage(SMSUtils.VALIDATE_CODE,telephone,code.toString());
            System.out.println("发送的验证码"+code);

            //设置key，来存放验证码
            String key=telephone+ RedisMessageConstant.SENDTYPE_ORDER;
            //将随机生成的验证码放入redis中，设置存放时间
            jedisPool.getResource().setex(key,60*10,code.toString());
            return new Result(true, MessageConstant.SEND_VALIDATECODE_SUCCESS);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false,MessageConstant.SEND_VALIDATECODE_FAIL);
        }
    }
}
